from mako.lookup import TemplateLookup
import simplejson
from django.db.models.fields.related import RelatedField
from modulefinder import ModuleFinder
from django.conf import settings
import re

class curry(object):
    def __init__(self, fun, *args, **kwargs):  
        self.fun = fun  
        self.pending = args[:]  
        self.kwargs = kwargs.copy()
    
    def __call__(self, *args, **kwargs):  
        if kwargs and self.kwargs:  
            kw = self.kwargs.copy()  
            kw.update(kwargs)  
        else:  
            kw = kwargs or self.kwargs
        
        return self.fun(*(self.pending + args), **kw)

import sys
   
def route(subdomain_mappings, request, controller='root', resource_id=None, method=None):
    module_name = get_app(request) + '.controllers.' + controller
    __import__(module_name)

    if not method:
        if resource_id: method = 'show'
        else: method = 'index'
        
    return getattr(sys.modules[module_name], method)(request, resource_id)

def get_app(request):
    for mapping in settings.DOMAIN_MAPPINGS:
        if request.get_host().startswith(mapping['subdomain']):
            return mapping['app']
    
rest_url_pattern = r'(?P<controller>[^/\?\&]+)(/(?P<resource_id>[^/\?\&]+))?(/(?P<method>[^/\?\&]+))?'

def rest_route(subdomain_mappings):
    return curry(route, subdomain_mappings)

def discover_controllers(controller_package):
    mf = ModuleFinder()
    controllers = mf.find_all_submodules(controller_package)
    
    urls = []
    for controller in controllers:
        urls.append((r'^' + controller + r'(/(?P<resource_id>[^/\?]*))?', curry(route, controller_package.__name__, resource=controller)))
    return tuple(urls)

import os
from django.http import HttpResponse, HttpResponseServerError
from mako.template import Template
from mako import exceptions

def render_to_response(filename, dictionary):
    templates = __import__(get_app(dictionary['request']) + '.templates').templates
    try:
        lookup = TemplateLookup(directories=[templates.__path__[0]], input_encoding='utf8')
        template = Template(filename=templates.__path__[0] + os.sep + filename, input_encoding='utf8', output_encoding='utf8', lookup=lookup)
        return HttpResponse(template.render(**dictionary))
    except:
        return HttpResponseServerError(exceptions.html_error_template().render())
    

#def get_template(name):
#    print __path__

def full_url(request):
    url = request.META['wsgi.url_scheme'] + "://" + request.META['SERVER_NAME']
    if request.META['SERVER_PORT'] != '80': url += ':' + request.META['SERVER_PORT']
    url += request.path
    if request.META['QUERY_STRING']: url += '?' + request.META['QUERY_STRING']
    return url

def url_prefix(request):
    url = request.META['wsgi.url_scheme'] + "://" + request.META['SERVER_NAME']
    if request.META['SERVER_PORT'] != '80': url += ':' + request.META['SERVER_PORT']
    return url

def to_json(queryset):
    result = []
    for obj in queryset:
        data = {}
        for field in obj._meta.fields:
            if isinstance(field, RelatedField): continue
            data[field.name] = unicode(obj.__getattribute__(field.name))
        result.append(data)
    return simplejson.dumps(result)
